package com.edu.boot.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.edu.boot.common.api.CommonResult;
import com.edu.boot.entity.News;
import com.edu.boot.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * @author Janson
 * @Description 系统公告
 * @Date 2025/4/10
 */
@RestController
public class NewsController {
    @Autowired
    private NewsService newsService;
    
    // 新增
    @PostMapping("news/add")
    public CommonResult addNews(@RequestBody News news) {
        newsService.save(news);
        return CommonResult.success();
    }
    
    // 删除
    @GetMapping("news/del/{id}")
    public CommonResult deleteNews(@PathVariable Integer id) {
        newsService.removeById(id);
        return CommonResult.success();
    }
    
    // 修改
    @PostMapping("news/update")
    public CommonResult updateNews(@RequestBody News news) {
        newsService.updateById(news);
        return CommonResult.success();
    }
    
    // 分页查询所有
    @GetMapping("news/list")
    public CommonResult getAllNews(@RequestParam(name = "currentpage") Integer current,
                             @RequestParam(name = "pagesize") Integer size,
                             @RequestParam(name = "title", required = false) String title) {
        Page<News> page = new Page<>(current, size);
        
        LambdaQueryWrapper<News> queryWrapper = new LambdaQueryWrapper<News>()
                .like(Objects.nonNull(title), News::getTitle, title)
                .orderByDesc(News::getAddtime);
        // 分页模糊查询
        Page<News> resultPage = newsService.page(page, queryWrapper);
        return CommonResult.success(resultPage);
    }
    
    // 根据 ID 查询
    @GetMapping("news/get/{id}")
    public CommonResult getNewsById(@PathVariable Integer id) {
        // 查询
        News newsInfo = newsService.getById(id);
        if (Objects.isNull(newsInfo)) return CommonResult.failed("未查询到相关信息！");
        // 点击次数+1
        newsInfo.setClicknum(newsInfo.getClicknum() + 1);
        // 更新
        newsService.updateById(newsInfo);
        return CommonResult.success(newsInfo);
    }
}
